<template>
  <a-drawer
    v-model:visible="visible"
    width="98%"
    unmount-on-close
    :title="`设计表单-${currentForm?.formName}`"
    @cancel="close"
  >
    <form-design ref="formDesignRef" />
    <template #footer>
      <a-button-group status="normal">
        <a-button
          :loading="loading"
          @click.stop="close"
        >
          <template #icon>
            <icon-close />
          </template>
          取消
        </a-button>
        <a-button
          type="primary"
          :loading="loading"
          @click.stop="saveDesign"
        >
          <template #icon>
            <icon-save />
          </template>
          确定
        </a-button>
      </a-button-group>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineExpose, nextTick, h } from 'vue';
import useLoading from '@/hooks/loading';
import { updateForm, SysFrom } from '@/api/system/form';
import { cloneDeep } from 'lodash';
import { FormItemConfig } from '@/components/form-design/item-select/config/type';
import { validateFormItemConfig } from '@/components/form-design/item-select/config/validate';
import { Message, Modal } from '@arco-design/web-vue';
import FormDesign from '@/components/form-design/index.vue';

const emits = defineEmits(['submit']);

const { loading, setLoading } = useLoading(false);

const visible = ref(false);

const currentForm = ref<SysFrom>({});

const formDesignRef = ref();
/**
 * 保存表单设计 信息到后端
 */
const saveDesign = () => {
  const { formConfig, formList } = formDesignRef.value.getConfig();
  if (!formConfig || !formList || formList.length <= 0) {
    Message.warning('请完善表单设计');
    return;
  }
  const formItem: FormItemConfig[] = [];
  const formPermission = {};
  const validateMessages: Array<string> = [];
  const formModel = {};
  getFormItem(formList, formItem, formPermission, formModel, validateMessages);
  if (validateMessages.length > 0) {
    Modal.error({
      title: '表单配置有误',
      content: () => {
        return validateMessages.map(item => h('p', item));
      },
      simple: true,
      hideCancel: true,
      cancelText: '取消',
      onOk: () => {
      }
    });
    return;
  }
  setLoading(true);
  currentForm.value.formConfig = formConfig;
  currentForm.value.formList = formList;
  currentForm.value.formItem = formItem;
  currentForm.value.formPermission = formPermission;
  currentForm.value.formModel = formModel;
  updateForm(currentForm.value).then(res => {
    visible.value = false;
    Message.success('操作成功');
    emits('submit');
  }).finally(() => {
    setLoading(false);
  });
};

/**
 * 获取表单项的值 并校验组件配置
 * @param formList
 * @param formItem
 * @param formPermission
 * @param formModel
 * @param validateMessages
 */
const getFormItem = (formList: FormItemConfig[], formItem: FormItemConfig[],
                     formPermission: any, formModel: any,
                     validateMessages: Array<string>) => {
  formList.forEach(item => {
    // 校验组件配置
    const result = validateFormItemConfig(item);
    if (result.status && result.message) {
      validateMessages.push(result.message);
    }
    if (item.group === 'container') {
      if (item.formList && item.formList.length > 0) {
        getFormItem(item.formList, formItem, formPermission, formModel, validateMessages);
      }
    } else {
      // todo 不是表单组件 如分割线需要排除  可编辑表格怎么处理
      formItem.push(item);
      if (item.id) {
        // 设置权限
        formPermission[item.id] = 'E';
        // 设置默认值
        formModel[item.id] = item.config.defaultValue ? item.config.defaultValue : undefined;
      }
    }
  });
};

const open = (sysForm: SysFrom) => {
  visible.value = true;
  currentForm.value = cloneDeep(sysForm);
  setLoading(false);
  nextTick(() => {
    formDesignRef.value.setConfig(sysForm.formConfig, sysForm.formList);
  });
};

const close = () => {
  visible.value = false;
};

defineExpose({
  open,
  close
});

</script>

<script lang="ts">
export default {
  name: 'DrawerDesign'
};
</script>

<style lang="less" scoped>

</style>